import { defineStore } from 'pinia'
import { login, getInfo } from '@/api/user'
export const useUserStore = defineStore(
  'user',
  () => {
    /**
     * 登录后获取到的信息
     */
    const userInfo = ref()
    const token = ref()

    // 存储个人信息
    const SET_USER = (payload) => {
      userInfo.value = payload
    }

    // 存储token
    const SET_TOKEN = (payload) => {
      token.value = payload
    }

    // 重置store
    const RESET_STORE = () => {
      userInfo.value = undefined
      token.value = undefined
    }

    // 登录
    const LOGIN = async (payload) => {
      return new Promise((resolve, reject) => {
        login(payload).then((res) => {
          if (res.code === 200) {
            SET_TOKEN(res.data)
            getInfo()
              .then((res) => {
                SET_USER(res.data)
                resolve(res)
              })
              .catch((err) => {
                reject(err)
              })
          } else {
            reject(res)
          }
        })
      })
    }

    // 登出
    const LOGOUT = () => {
      return new Promise((resolve, reject) => {
        RESET_STORE()
        resolve()
      })
    }

    return {
      userInfo,
      token,
      LOGIN,
      LOGOUT,
    }
  },
  {
    persist: {
      key: 'user_key',
      paths: ['userInfo', 'token'],
    },
  },
)
